<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class Field extends Common
{
    protected $field_type;

    function __construct()
    {
        parent::__construct();
        $field_pattern = config("fieldVerify.verify");
        $this->assign('pattern', $field_pattern);
        $this->field_type = config("fieldType.type");

    }

    /**
     * 获取模型字段列表
     * @author admin
     * @date 2019-08-08
     */

    public function index()
    {
        if (request()->isPost()) {
            $mid = input('post.mid');
            $nodostatus = array('catid', 'title', 'status', 'createtime');
            $sysfield = array('catid', 'userid', 'username', 'title', 'thumb', 'keywords', 'description', 'posid', 'status', 'createtime', 'url', 'template');

            $list = Db::name('field')->where("moduleid", $mid)->order('sort asc,id asc')->select()->toArray();
            foreach ($list as $k => $v) {
                if ($v['status'] == 1) {
                    if (in_array($v['field'], $nodostatus)) {
                        $list[$k]['disable'] = 2;
                    } else {
                        $list[$k]['disable'] = 0;
                    }
                } else {
                    $list[$k]['disable'] = 1;
                }

                if (in_array($v['field'], $sysfield)) {
                    $list[$k]['delStatus'] = 1;
                } else {
                    $list[$k]['delStatus'] = 0;
                }
            }
            $this->assign('list', $list);
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list, 'rel' => 1];
        } else {
            $mid = input("request.mid", 0, "intval");
            if (!$mid) {
                return $result = ['code' => 1, 'msg' => '非法请求'];
            }
            $title = db::name("module")->where("id", $mid)->value('title');
            $this->assign("title", $title);
            return View::fetch();
        }
    }


    /**
     * 获取字段类型返回参数HTML
     * @author admin
     * @date 2019-08-08
     */

    public function fieldType()
    {
        $this->assign(input('get.'));
        $this->assign(input('post.'));
        $name = Db::name('module')->where('id', input('mid'))->value('name');
        if (input('name')) {
            $files = Db::getTableFields(config('database.connections.mysql.prefix') . $name);
            if (isset($files['type'])) {
                $fieldtype = $files['type'][input('name')];
                $this->assign('fieldtype', $fieldtype);
            }
            return view('editType');
        } else {
            return view('type');
        }
    }

    /**
     * 添加字段
     * @author admin
     * @date 2019-08-08
     */
    public function add()
    {
        try {
            if (Request::isPost()) {
                config('database.fields_strict', false);
                $data = input('post.');
                $fieldName = $data['field'];
                $prefix = config('database.connections.mysql.prefix');
                $name = Db::name('module')->where('id', $data['moduleid'])->value('name');
                $tablename = $prefix . $name;
                $Fields = Db::getTableFields($tablename);
                if (in_array($fieldName, $Fields)) {
                    return ['code' => 0, 'msg' => '字段名已经存在！'];
                }
                $addfieldsql = $this->get_tablesql($data, 'add');
                if (isset($data['setup'])) {
                    $data['setup'] = array2string($data['setup']);
                }
                $data['status'] = 1;
                if (empty($data['class'])) {
                    $data['class'] = $data['field'];
                }
                $model = db::name('field');
                if ($model->insert($data) !== false) {
                    if (is_array($addfieldsql)) {
                        foreach ($addfieldsql as $sql) {
                            $model->execute($sql);
                        }
                    } else {
                        $model->execute($addfieldsql);
                    }
                    return ['code' => 0, 'msg' => '添加成功！'];
                } else {
                    return ['code' => 1, 'msg' => '添加失败！'];
                }
            } else {
                $mid = input('mid', 0, "intval");
                if (!$mid) return ['code' => 1, 'msg' => '非法请求！'];
                $fieldType = Db::name('field')->where('moduleid', $mid)->column('type');
                if (in_array('catid', $fieldType)) {
                    unset($this->field_type[0]);
                };
                if (in_array('title', $fieldType)) {
                    unset($this->field_type[1]);
                }
                $this->assign('type', $this->field_type);
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 编缉字段
     * @author admin
     * @date 2019-08-08
     */
    public function edit()
    {
        try {
            if (Request::isPost()) {
                $data = Request::except(['oldfield']);
                $oldfield = input('oldfield');
                $fieldName = $data['field'];
                $name = Db::name('module')->where(array('id' => $data['moduleid']))->value('name');
                $prefix = config('database.connections.mysql.prefix');
                if ($this->_iset_field($prefix . $name, $fieldName) && $oldfield != $fieldName) {
                    return ['code' => 1, 'msg' => '字段名重复！'];
                }
                $editfieldsql = $this->get_tablesql(input('post.'), 'edit');
                if (isset($data['setup'])) {
                    $data['setup'] = array2string($data['setup']);
                }
                if (!empty($data['unpostgroup'])) {
                    $data['setup'] = implode(',', $data['unpostgroup']);
                }
                if (empty($data['class'])) {
                    $data['class'] = $data['field'];
                }

                $model = db::name('field');
                if (false !== $model->update($data)) {
                    if (is_array($editfieldsql)) {
                        foreach ($editfieldsql as $sql) {
                            $model->execute($sql);
                        }
                    } else {
                        $editfieldsql;
                        $model->execute($editfieldsql);
                    }
                    return ['code' => 0, 'msg' => '修改成功！'];
                } else {
                    return ['code' => 1, 'msg' => '修改失败！'];
                }
            } else {
                $model = db::name('field');
                $id = input('param.id');
                if (empty($id)) {
                    return ['code' => 1, 'msg' => '缺少必要的参数！'];
                }
                $fieldInfo = $model->where(array('id' => $id))->find();
                if ($fieldInfo['setup']) $fieldInfo['setup'] = string2array($fieldInfo['setup']);
                $this->assign('info', $fieldInfo);
                $this->assign('type', $this->field_type);
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 修改是否必填
     * @author admin
     * @date 2019-08-08
     */
    public function requiredChange()
    {
        try {
            $id = input('post.id');
            $required = input('post.required');
            $data['required'] = $required;
            Db::name('field')->where("id", $id)->update($data);
            return ['code' => 0, 'msg' => '操作成功！'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 修改启用禁用状态
     * @author admin
     * @date 2019-08-08
     */
    public function doStatus()
    {
        try {
            $id = input('post.id');
            //判断当前状态情况
            $status = Db::name('field')->where("id", $id)->value('status');
            if ($status == 1) {
                $data['status'] = 0;
            } else {
                $data['status'] = 1;
            }
            Db::name('field')->where("id", $id)->update($data);
            return ['code' => 0, 'msg' => '编辑成功！'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 字段排序
     * @author admin
     * @date 2019-08-08
     */
    public function order()
    {
        try {
            $data = input('post.');
            if (Db::name('field')->update($data) !== false) {
                return ['code' => 0, 'msg' => '操作成功！'];
            } else {
                return ['code' => 1, 'msg' => '操作失败！'];
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 删除字段
     * @author admin
     * @date 2019-08-08
     */
    public function doDelete()
    {
        try {
            $id = input('id');
            if (!$id) return ['code' => 1, 'msg' => '非法请求！'];

            $r = Db::name('field')->find($id);
            Db::name('field')->delete($id);
            $moduleid = $r['moduleid'];
            $field = $r['field'];
            $prefix = config('database.connections.mysql.prefix');
            $name = Db::name('module')->where(array('id' => $moduleid))->value('name');
            $tablename = $prefix . $name;
            Db::execute("ALTER TABLE `$tablename` DROP column `$field`");
            return ['code' => 0, 'msg' => '删除成功！'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 生成字段操作SQL语句
     * @author admin
     * @date 2019-08-08
     */
    public function get_tablesql($info, $do)
    {
        $comment = $info['name'];
        $fieldtype = $info['type'];
        if (isset($info['setup']['fieldtype'])) {
            $fieldtype = $info['setup']['fieldtype'];
        }
        $moduleid = $info['moduleid'];
        $default = isset($info['setup']['default']) ? $info['setup']['default'] : '';

        $isnull = $info['required'] == 0 ? 'NULL' : "NOT NULL";

        $field = $info['field'];
        $prefix = config('database.connections.mysql.prefix');
        $name = db::name('module')->where(array('id' => $moduleid))->value('name');
        $tablename = $prefix . $name;
        $maxlength = intval($info['maxlength']);
        $minlength = intval($info['minlength']);
        if (isset($info['setup']['numbertype'])) {
            $numbertype = $info['setup']['numbertype'];
        }
        if (isset($info['oldfield'])) {
            $oldfield = $info['oldfield'];
        }
        if ($do == 'add') {
            $do = ' ADD ';
        } else {
            $do = " CHANGE `" . $oldfield . "` ";
        }
        switch ($fieldtype) {
            case 'varchar':
                if (!$maxlength) {
                    $maxlength = 255;
                }
                $maxlength = min($maxlength, 255);
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'title':
                $thumb = $info['setup']['thumb'];
                $style = $info['setup']['style'];
                if (!$maxlength) {
                    $maxlength = 255;
                }
                $maxlength = min($maxlength, 255);
                $sql[] = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) $isnull DEFAULT '$default' COMMENT '$comment'";


                if (!$this->_iset_field($name, 'thumb')) {
                    if ($thumb == 1) {
                        $sql[] = "ALTER TABLE `$tablename` ADD `thumb` VARCHAR( 100 ) $isnull DEFAULT '' COMMENT '缩略图'";
                    }
                } else {
                    if ($thumb == 0) {
                        $sql[] = "ALTER TABLE `$tablename` drop column `thumb`";
                    }
                }

                if (!$this->_iset_field($name, 'title_style')) {
                    if ($style == 1) {
                        $sql[] = "ALTER TABLE `$tablename` ADD `title_style` VARCHAR( 100 ) $isnull DEFAULT '' COMMENT '标题样式'";
                    }
                } else {
                    if ($style == 0) {
                        $sql[] = "ALTER TABLE `$tablename` drop column `title_style`";
                    }
                }
                break;
            case 'catid':
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED $isnull DEFAULT '0' COMMENT '$comment'";
                break;

            case 'number':
                $decimaldigits = $info['setup']['decimaldigits'];
                $default = $decimaldigits == 0 ? intval($default) : floatval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` " . ($decimaldigits == 0 ? 'INT' : 'decimal( 10,' . $decimaldigits . ' )') . " " . ($numbertype == 1 ? 'UNSIGNED' : '') . "  $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'tinyint':
                if (!$maxlength) $maxlength = 3;
                $maxlength = min($maxlength, 3);
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT( $maxlength ) " . ($numbertype == 1 ? 'UNSIGNED' : '') . " $isnull DEFAULT '$default' COMMENT '$comment'";
                break;


            case 'smallint':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT " . ($numbertype == 1 ? 'UNSIGNED' : '') . " $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'int':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` INT " . ($numbertype == 1 ? 'UNSIGNED' : '') . " $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'mediumint':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` INT " . ($numbertype == 1 ? 'UNSIGNED' : '') . " $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'mediumtext':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT $isnull COMMENT '$comment'";
                break;

            case 'text':
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT $isnull COMMENT '$comment'";
                break;

            case 'posid':
                $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT(2) UNSIGNED $isnull DEFAULT '0' COMMENT '$comment'";
                break;

            case 'datetime':
                $sql = "ALTER TABLE `$tablename` $do `$field` INT(11) UNSIGNED $isnull DEFAULT '0' COMMENT '$comment'";
                break;

            case 'editor':
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT $isnull COMMENT '$comment'";
                break;

            case 'image':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;

            case 'images':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT $isnull COMMENT '$comment'";
                break;

            case 'file':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;

            case 'files':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT $isnull COMMENT '$comment'";
                break;
            case 'template':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;
            case 'linkage':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;
        }
        return $sql;
    }

    /**
     * 获取表已有字段
     * @author admin
     * @date 2019-08-08
     */
    protected function _iset_field($table, $field)
    {
        $fields = Db::getTableFields($table);
        return array_search($field, $fields);
    }

}